package com.itheima.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupMapper checkGroupMapper;
    @Autowired
    private CheckItemMapper checkItemMapper;
    @Override
    @Transactional
    public void add(Integer[] checkitemIds, CheckGroup checkGroup) {
        checkGroupMapper.addGroup(checkGroup);
        checkGroupMapper.addItems(checkitemIds,  checkGroup.getId());
    }

    @Override
    @Transactional
    public int delete(Integer id) {
        //判断检查组是否关联了套餐
        int count = checkGroupMapper.findCountBySetmealId(id);
        if(count>0){
            return -1;
        }
        //删除检查组关联的检查项
        List<Integer> itemIds = checkItemMapper.findCheckItemIdsByCheckGroupId(id);
        if(itemIds.size()>0){
            for (Integer itemId : itemIds) {
                checkItemMapper.deleteById(itemId,  id);
            }
        }
        return checkGroupMapper.delete(id);
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer setmealId) {
        return checkGroupMapper.findCheckGroupIdsBySetmealId(setmealId);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        PageInfo<CheckGroup> pageInfo = new PageInfo<>
                (checkGroupMapper.findPage(queryPageBean.getQueryString()));
        return  new PageResult(pageInfo.getTotal(),  pageInfo.getList());
    }

    @Override
    @Transactional
    public void edit(Integer[] checkitemIds, CheckGroup checkGroup) {
        checkGroupMapper.edit(checkGroup);
        //删除检查组关联的检查项
        List<Integer> itemIds = checkItemMapper.findCheckItemIdsByCheckGroupId(checkGroup.getId());
        if(itemIds.size()>0){
            for (Integer itemId : itemIds) {
                checkItemMapper.deleteById(itemId,  checkGroup.getId());
            }
        }
        //添加新的检查项关联
        checkGroupMapper.addItems(checkitemIds,  checkGroup.getId());
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupMapper.findAll();

    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupMapper.findById(id);

    }
}
